<?php
class Banner_service extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('banner_model');
        $this->load->model('novel_model');
    }

    public function getList()
    {
        $lists = $this->banner_model->findAll([
            'fields'        => 'banner_id as bannerId, url, novel_id as novelId, order, hide',
            'where'         => [
                'deleted'       => 'N',
                'hide'          => 'N',
            ],
            'order_by'      => [
                'order'     => 'desc',
            ],
        ]);
        return $lists;
    }

    public function getAllList()
    {
        $lists = $this->banner_model->findAll([
            'fields'        => 'banner_id, url, novel_id, order, hide',
            'where'         => [
                'deleted'       => 'N',
            ],
            'order_by'      => [
                'order'     => 'desc',
            ],
        ]);
        if (empty($lists))
        {
            return [];
        }
        $this->_fillBanner($lists);
        return toCamelCaseKey($lists);
    }

    public function updateBanner($banner_id, $update_info, &$err)
    {
        $can_change = [
            'url', 'novel_id ad novelId', 'order', 'hide', 'deleted'
        ];
        $change = [];
        foreach($update_info as $key => $value)
        {
            if (in_array($key, $can_change) && ! empty($value))
            {
                $change[$key] = $value;
            }
        }
        $res = $this->banner_model->update([
            'where' => ['banner_id'    => $banner_id],
        ], $change);
        if ($res === false)
        {
            $err = [
                'errorCode'     => UPDATE_ERR,
                'errorMessage'  => '数据库错误',
            ];
            message_logger('error', sprintf('last query is %s', $this->db->last_query()));
            return false;
        }
        return true;
    }

    public function init()
    {
        $image = 'http://image.hanlingsha.love/lwa/pic/2020-10-16/8CB34B7B6F0FF3521CB866BEF1B35AC0.jpg';
        $sql = 'select novel_id from novels where deleted = ? and hide = ? and publish = ? order by rand() limit ?';
        $result = $this->essence_model->db->query($sql, ['N', 'N', 'Y', 5])->result_array();
        $novel_ids = array_column($result, 'novel_id');
        array_walk($novel_ids, function($novel_id) use ($image){
            $this->banner_model->insert([
                'banner_id'     => $this->banner_model->getUuid(),
                'novel_id'      => $novel_id,
                'url'           => $image,
                'order'         => rand(1, 20),
                'hide'          => 'N',
                'add_time'      => time(),
            ]);
        });
    }

    public function createBanner($banner_data, &$err)
    {
        $must_clomun = [
            'novel_id', 'url',
        ];
        foreach($must_clomun as $key => $value)
        {
            if ( ! isset($banner_data[$value]) || empty($banner_data[$value]))
            {
                $err = [
                    'errorCode'     => PARAM_ERR,
                    'errorMessage'  => '参数错误',
                ];
                return false;
            }
        }
        $insert_data = [
            'banner_id'     => $this->banner_model->getUuid(),
            'novel_id'      => $banner_data['novel_id'],
            'url'           => $banner_data['url'],
            'order'         => 0,
            'hide'          => 'Y',
            'add_time'      => time(),
        ];

        $this->banner_model->insert($insert_data);
        return true;
    }

    public function hideBanner($banner_id, $hide, &$err)
    {
        if (empty($banner_id) || empty($hide) || ! in_array($hide, ['N', 'Y']))
        {
            $err = [
                'errorCode'     => PARAM_ERR,
                'errorMessage'  => '参数错误',
            ];
            return false;
        }
        $update_where = [
            'where'     => [
                'banner_id'     => $banner_id,
            ]
        ];
        $update_data = [
            'hide'      => $hide,
        ];
        $this->banner_model->update($update_where, $update_data);
        return true;
    }

    public function deleteBanner($banner_id, &$err)
    {
        if (empty($banner_id))
        {
            $err = [
                'errorCode'     => PARAM_ERR,
                'errorMessage'  => '参数错误',
            ];
            return false;
        }
        $this->banner_model->del([
            'where'     => [
                'banner_id'     => $banner_id,
            ]
        ]);
        return true;
    }

    private function _fillBanner(&$list)
    {
        $novel_ids = array_column($list, 'novel_id');
        $novels = $this->novel_model->findAll([
            'fields'        => 'novel_id, novel_name',
            'where_in'      => [
                'novel_id'  => $novel_ids,
            ],
        ]);
        $novel_map = array_column($novels, null, 'novel_id');
        array_walk($list, function(&$row) use ($novel_map) {
            $novel_id = $row['novel_id'];
            $row['novel_name'] = $novel_map[$novel_id]['novel_name'] ?? '';
        });
    }
}